package com.example.demo.consumer.config;

import com.example.demo.common.domain.ChannelRead;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;

/**
 * @Auther Created by l.wang on 2019/4/4.
 */
@EnableJms
@Configuration
public class ActiveMqConfig {


    @Bean
    public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory,
                                                    DefaultJmsListenerContainerFactoryConfigurer configurer) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setMessageConverter(jacksonJmsMessageConverter());
        // This provides all boot's default to this factory, including the message converter
        configurer.configure(factory, connectionFactory);
        // You could still override some of Boot's default if necessary.
        return factory;
    }

    @Bean // Serialize message content to json using TextMessage
    public MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");
        return converter;
    }

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Bean
    public ServiceEventSource serviceEventSource() {
        return new ServiceEventSource(jmsMessagingTemplate);
    }

    public static class ServiceEventSource {

        private JmsMessagingTemplate jmsMessagingTemplate;

        public ServiceEventSource(JmsMessagingTemplate jmsMessagingTemplate) {
            this.jmsMessagingTemplate = jmsMessagingTemplate;
        }

        public void publishToConnectServer(ChannelRead res) {
            jmsMessagingTemplate.convertAndSend("queue.connectServices:" + res.getFinger(), res);
        }
    }

    @Bean
    public Queue queue(){
        return new ActiveMQQueue("test_activemq");
    }


}
